package leetcode.editor.cn;

/**
 * ******************************************************
 *
 * @author liugh9
 * @version 1.0
 * @classname BST
 * @description
 * @date 2023/04/16 10:32
 * <p>
 * ******************************************************
 */
public class BST {
    public boolean isValidBST(TreeNode root) {
        return isValidBST(root, null, null);
    }

    /**
     * 限定以 root 为根的子树节点必须满足 max.val > root.val > min.val
     *
     * @param root 当前节点
     * @param min  右子树中当前节点上方的的最大值
     * @param max  左子树中当前节点上方的的最小值
     * @return
     */
    private boolean isValidBST(TreeNode root, TreeNode min, TreeNode max) {
        if (root == null) {
            return true;
        }
        if (min != null && root.val <= min.val) return false;
        if (max != null && root.val >= max.val) return false;
        return isValidBST(root.left, min, root) && isValidBST(root.right, root, max);
    }

    public TreeNode searchBST(TreeNode root, int val) {
        if (root == null) {
            return null;
        }
        if (root.val == val) {
            return root;
        }
        if (root.val > val) {
            return searchBST(root.left, val);
        }
        return searchBST(root.right, val);
    }

    public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return null;
        }
        if (root.val == key) {
            // 如果至少有一个子节点为空，之后升级的节点就是另外一个节点
            if (root.left == null) return root.right;
            if (root.right == null) return root.left;
            // 可采用右子树最小值或者左子树最大值来替代当前位置
            // 这里采用右子树最小值
            TreeNode minNode = getRightMin(root.right);
            // 交换两者位置
            // 删除最小值
            root.right = deleteNode(root.right, minNode.val);
            // 用右子树最小的节点替换 root 节点
            minNode.left = root.left;
            minNode.right = root.right;
            root = minNode;

        } else if (root.val > key) {
            root.left = deleteNode(root.left, key);
        } else {
            root.right = deleteNode(root.right, key);
        }
        return root;
    }

    private TreeNode getRightMin(TreeNode right) {
        // BST 最左边的就是最小的
        while (right.left != null) right = right.left;
        return right;
    }

    public TreeNode insertIntoBST(TreeNode root, int val) {
        if (root == null) {
            return new TreeNode(val);
        } else if (root.val > val) {
            root.left = insertIntoBST(root.left, val);
        } else {
            root.right = insertIntoBST(root.right, val);
        }
        return root;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
